import { useState } from 'react';
import { Button, Space, Spin, Modal } from 'antd';
import { Redirect } from 'react-router-dom';
import classNames from 'classnames';
import markdown from '../../../lib/markdown';

import Api from '../../../api';
import styles from './index.module.css';

function saveMd(postId: number | undefined, title: string, content: string) {
  return Api.Post.savePost({ postId, title, content, format: 'md' });
}

enum PageStatus {
  /**
   * 编辑中
   */
  EDITING,
  /**
   * 保存成功
   */
  SAVED,
}

export default function PagePostEditor(post: { title?: string; content?: string; postId?: number }) {
  const [title, setTitle] = useState(post.title || '');
  const [content, setContent] = useState(post.content || '');
  const [postId, setPostId] = useState<number | undefined>(post.postId || undefined);
  const [renderedContent, setRenderedContent] = useState('');

  const [status, setStatus] = useState<PageStatus>(PageStatus.EDITING);
  const [spinning, setSpinning] = useState<boolean>(false);

  const save = () => {
    setSpinning(true);
    saveMd(postId, title, content)
      .then(({ postId }) => {
        setSpinning(false);
        setPostId(postId);
        setStatus(PageStatus.SAVED);
      })
      .catch((err) => {
        setSpinning(false);
        Modal.error({
          title: '保存失败',
          content: `失败原因：${err.message}`,
          zIndex: 1000000,
        });
      });
  };

  switch (status) {
    case PageStatus.SAVED:
      return <Redirect to={`/p/${postId}`} />;
    case PageStatus.EDITING:
      return (
        <div className={styles['page']}>
          <input
            value={title}
            className={classNames(styles['title'], styles['input'])}
            onChange={(e) => setTitle(e.target.value)}
            placeholder="请在此填写文章标题"
          />
          <div className={styles['editor']}>
            <textarea
              className={classNames(styles['raw'], styles['input'])}
              value={content}
              onChange={(e) => {
                const newContent = e.target.value;
                setContent(newContent);
                setRenderedContent(markdown(newContent));
              }}
              placeholder="请在此填写文章内容"
            />
            <div className={styles['preview']} dangerouslySetInnerHTML={{ __html: renderedContent }}></div>
          </div>
          <div className={styles['footer']}>
            <Spin spinning={spinning} tip="保存">
              <Space>
                <Button>取消</Button>
                <Button type="primary" onClick={save}>
                  保存
                </Button>
              </Space>
            </Spin>
          </div>
        </div>
      );
  }
}
